package page

import (
	"ibdreader/mysql_def"
	"ibdreader/slice"
)

/*
	https://dev.mysql.com/doc/internals/en/innodb-fil-header.html
	The Fil Header has eight parts, as follows (38 byte):
	+-------------------------------------------------------------------------------------------------------------------------------------------------+
	+	Name 						+ Size 	+  	Remarks														                                          +
	+-------------------------------------------------------------------------------------------------------------------------------------------------+
	+	FIL_PAGE_SPACE 				+  4    +	4 ID of the space the page is in							                                          +
	+	FIL_PAGE_OFFSET   			+  4    +	ordinal page number from start of space                                                               +
	+	FIL_PAGE_PREV   			+  4    +	offset of previous page in key order                                                                  +
	+	FIL_PAGE_NEXT     			+  4    + 	offset of next page in key order                                                                      +
	+	FIL_PAGE_LSN    			+  8    +	log serial number of page's latest log record                                                         +
	+	FIL_PAGE_TYPE    			+  2    +	current defined types are: FIL_PAGE_INDEX, FIL_PAGE_UNDO_LOG, FIL_PAGE_INODE, FIL_PAGE_IBUF_FREE_LIST +
	+	FIL_PAGE_FILE_FLUSH_LSN   	+  8    +	"the file has been flushed to disk at least up to this lsn"                                           +
	+								+		+ 	(log serial number), valid only on the first page of the file                                         +
	+	FIL_PAGE_ARCH_LOG_NO    	+  4   	+	the latest archived log file number at the time that FIL_PAGE_FILE_FLUSH_LSN was written (in the log) +
	+-------------------------------------------------------------------------------------------------------------------------------------------------+
*/
type FilHeader struct {
	PageSpace        int64
	PageOffset       int64
	PagePrev         int64
	PageNext         int64
	PageLsn          int64
	PageType         string
	PageFileFlushLsn int64
	PageArchLogNo    int64
}

func FileHeaderReadSlice(pos int64) FilHeader {
	var fh FilHeader
	slice.SetPosition(pos)
	fh.PageSpace = slice.ReadUnsignedInt()
	fh.PageOffset = slice.ReadUnsignedInt()
	fh.PagePrev = slice.IfUndefined(slice.ReadUnsignedInt())
	fh.PageNext = slice.IfUndefined(slice.ReadUnsignedInt())
	fh.PageLsn = slice.ReadLongInt64()
	fh.PageType = mysql_def.ParsePageType(slice.ReadShortInt16())
	fh.PageFileFlushLsn = slice.ReadLongInt64()
	fh.PageArchLogNo = slice.ReadUnsignedInt()
	return fh
}

func IsRootPage(fh FilHeader) bool {
	if fh.PagePrev == -1 && fh.PageNext == -1 {
		return true
	}
	return false
}
